package com.lagou.config;

import com.lagou.pojo.Configuration;
import com.lagou.pojo.MappedStatement;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class XMLMapperBuilder {
    private Configuration configuration;

    public XMLMapperBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    public Configuration parse(InputStream resourceAsSteam) throws DocumentException {
        SAXReader reader = new SAXReader();
        Document read = reader.read(resourceAsSteam);
        org.dom4j.Element rootElement = read.getRootElement();
        Map<String, MappedStatement> MappedStatements = new HashMap<String, MappedStatement>();
        MappedStatements = parseTag(rootElement, MappedStatements, "select");
        MappedStatements = parseTag(rootElement, MappedStatements, "insert");
        MappedStatements = parseTag(rootElement, MappedStatements, "delete");
        MappedStatements = parseTag(rootElement, MappedStatements, "update");
        configuration.setMappedStatement(MappedStatements);
        return configuration;
    }

    private Map<String, MappedStatement> parseTag(Element rootElement, Map<String, MappedStatement> mappedStatements, String sqlType) {
        String namespace = rootElement.attributeValue("namespace");
        List<org.dom4j.Element> childElements = rootElement.elements(sqlType);
        for (int index = 0; index < childElements.size(); index++) {
            org.dom4j.Element element = childElements.get(index);
            String id = element.attributeValue("id");
            String resultType = element.attributeValue("resultType");
            String paramType = element.attributeValue("paramType");
            String sql = element.getTextTrim();
            MappedStatement mappedStatement = new MappedStatement();
            mappedStatement.setId(id);
            mappedStatement.setParamType(paramType);
            mappedStatement.setResultType(resultType);
            mappedStatement.setSql(sql);
            mappedStatement.setSqlType(sqlType);
            mappedStatements.put(namespace + "." + id, mappedStatement);
        }
        return mappedStatements;
    }

}
